import 'dart:async';

import 'package:adaptivex/adaptivex.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:flutter/material.dart';

import '../../constant/db_constant.dart';
import '../../constant/edit_constant.dart';
import '../../db/entity/AttributeBean.dart';
import '../../main.dart';
import '../../three/datatable/datatable_header.dart';
import '../../three/datatable/responsive_datatable.dart';
import '../../widgets/gyy_dialog.dart';
import '../../widgets/gyy_theme.dart';
import 'attribute_drop_view.dart';
import '../../widgets/page.dart';
import 'edit_attribute.dart';

///新增，删除，属性
///列表

class AttributeIndexPage extends StatefulWidget {
  const AttributeIndexPage({Key? key}) : super(key: key);

  @override
  State<AttributeIndexPage> createState() => _EditAttributeState();
}

class _EditAttributeState extends State<AttributeIndexPage> with PageMixin {
  late List<DatatableHeader> _headers;

  var attributeDao = database.attributeDao;
  List<AttributeBean> allList = [];
  List<AttributeBean> levelOneList = [];
  TextEditingController attributeNameController = TextEditingController();
  TextEditingController attributeCodeController = TextEditingController();

  //每页的数量 数组
  final List<int> _perPages = [10, 20, 50, 100];

  //每页的数量 当前的
  int _currentPerPage = 10;

  //当前页
  int _currentPage = 1;
  int _total = 100;

  final List<Map<String, dynamic>> _sourceOriginal = [];
  List<Map<String, dynamic>> _sourceFiltered = [];
  List<Map<String, dynamic>> _sourceList = []; //

  //选中的一级数据
  List<Map<String, dynamic>> _selectedList = [];

  //选中的一级数据 code
  String? selectParentCode;

  //勾选的数据id （为了解决刷新数据后，对象地址改变，所以用id比对）
  int? selectId;

  //选中的二级属性
  Map<String, dynamic> selectedSub = {};

  //展开的一级属性
  Map<String, dynamic> expandedData = {};

  String? _sortColumn;
  final bool _sortAscending = true;
  bool _isLoading = true;
  late Timer delayedTimer;

  final String _searchKey1 = DbConstant.attribute_name;
  final String _searchKey2 = DbConstant.attribute_code;

  //加载所有的
  loadAll() async {
    allList = await attributeDao.findAll();
    levelOneList =
        allList.where((element) => element.attributeLevel == 1).toList();

    _pullData();
  }

  //加载二级属性
  Future<List<AttributeBean>> loadChildren(String code) async {
    return await attributeDao.findByParentCode(code);
  }

  //新增属性
  addOne(String name, String code) async {
    if (selectParentCode == null) {
      debugPrint('1--属性：' + name + '  ' + code);
      //保存1级属性
      await attributeDao.insertOne(AttributeBean(
          attributeName: name,
          attributeCode: code,
          attributeValue: '',
          attributeLevel: 1,
          parentCode: '',
          searchType: 0,
          createTime: DateTime.now(),
          updateTime: DateTime.now()));
    } else {
      debugPrint('2--属性：' + name + '  ' + code + ' = ' + selectParentCode!);
      //保存2级属性
      await attributeDao.insertOne(AttributeBean(
          attributeName: name,
          attributeCode: code,
          attributeValue: '',
          attributeLevel: 2,
          parentCode: selectParentCode!,
          searchType: 0,
          createTime: DateTime.now(),
          updateTime: DateTime.now()));
    }
    showMessage(context, StringConstant.saveSuccess);
  }

  deleteOne(int id) async {
    await attributeDao.deleteById(id);
    //删除，清空
    selectParentCode = null;
    await loadAll();
  }

  bool checkInput() {
    if (attributeNameController.text.isEmpty) {
      showMessage(context, '请输入属性名称');
      return false;
    }
    if (attributeCodeController.text.isEmpty) {
      showMessage(context, '请输入属性编号');
      return false;
    }
    return true;
  }

  //加载数据
  _pullData() async {
    setState(() => _isLoading = true);
    delayedTimer = Timer(delayedDuration, () {
      _sourceOriginal.clear();
      _sourceOriginal.addAll(_generateData(levelOneList));
      _sourceFiltered = _sourceOriginal;
      _total = _sourceFiltered.length;
      if (_currentPerPage > _sourceOriginal.length) {
        _sourceList =
            _sourceFiltered.getRange(0, _sourceOriginal.length).toList();
      } else {
        _sourceList = _sourceFiltered.getRange(0, _currentPerPage).toList();
      }
      setState(() => {_isLoading = false});
    });
  }

  //重置数据
  _resetData({start = 0}) async {
    setState(() => _isLoading = true);
    var _pageLength =
        _total - start < _currentPerPage ? _total - start : _currentPerPage;
    fluent.debugPrint(start.toString() + " - " + _pageLength.toString());

    Future.delayed(const Duration(seconds: 0)).then((value) {
      _sourceList.clear();
      _sourceList =
          _sourceFiltered.getRange(start, start + _pageLength).toList();
      setState(() => _isLoading = false);
    });
  }

  //过滤数据
  _filterData() {
    setState(() => _isLoading = true);
    final name = attributeNameController.text;
    final code = attributeCodeController.text;
    try {
      if (name == '' && code == '') {
        _sourceFiltered = _sourceOriginal;
      } else {
        _sourceFiltered = _sourceOriginal
            .where((data) =>
                (data[_searchKey1]
                        .toString()
                        .toLowerCase()
                        .contains(name.toLowerCase()) &&
                    name != '') ||
                (data[_searchKey2]
                        .toString()
                        .toLowerCase()
                        .contains(code.toLowerCase()) &&
                    code != ''))
            .toList();
      }

      _total = _sourceFiltered.length;
      var _rangeTop = _total < _currentPerPage ? _total : _currentPerPage;
      _sourceList = _sourceFiltered.getRange(0, _rangeTop).toList();
    } catch (e) {
      debugPrint(e.toString());
    }
    setState(() => _isLoading = false);
  }

  @override
  void initState() {
    super.initState();

    /// set headers
    _headers = _generateHeader();
    loadAll(); //加载所有产品
  }

  @override
  void dispose() {
    super.dispose();
    delayedTimer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
          Container(
            margin: const EdgeInsets.all(10),
            constraints: const BoxConstraints(
              maxHeight: 800,
            ),
            child: Card(
              child: ResponsiveDatatable(
                reponseScreenSizes: const [ScreenSize.xs],
                actions: generateActions(),
                headers: _headers,
                source: _sourceList,
                selecteds: _selectedList,
                selectId: selectId,
                showSelect: true,
                autoHeight: false,
                expandedData: expandedData,
                //展开的对象
                sortAscending: _sortAscending,
                sortColumn: _sortColumn,
                isLoading: _isLoading,
                //下拉内容
                dropContainer: (data) {
                  return Card(
                    child: FutureBuilder<List<AttributeBean>>(
                      future: loadChildren(data["attributeCode"]),
                      builder: (context, snapshot) {
                        if (snapshot.data == null || snapshot.data!.isEmpty) {
                          return const Text(StringConstant.inputHand);
                        } else {
                          return AttributeDropView(
                            _generateData(snapshot.data!),
                            selectedSub,
                            _generateHeader(),
                            onSelect: (value, item) {
                              debugPrint("$value === $item ");
                              if (value) {
                                //sub选中，一级属性选中 全部取消
                                _selectedList = [];
                                //记录sub选中
                                selectedSub = item;
                                selectId = item['id'];
                              } else {
                                selectedSub = {};
                                selectId = null;
                              }
                              setState(() {});
                            },
                          );
                        }
                      },
                    ),
                  );
                },
                onDrop: (value, item) {
                  // debugPrint("$value == $item ");
                  if (value!) {
                    //记录展开数据
                    expandedData = item;
                  } else {
                    expandedData = {};
                    //收起的时候，sub全部取消选中
                    selectedSub = {};
                  }
                },
                onSelect: (value, item) {
                  debugPrint("$value == $item ");
                  if (value!) {
                    if (_selectedList.isNotEmpty) {
                      _selectedList = [];
                    }
                    setState(() => {
                          _selectedList.add(item),
                          selectParentCode = item['attributeCode'],
                          selectId = item['id'],
                          selectedSub = {},
                        });
                  } else {
                    var index = _selectedList.indexOf(item);
                    if (index != -1) {
                      _selectedList.removeAt(index);
                    }
                    selectParentCode = null;
                    selectId = null;
                    setState(() => {});
                  }
                },
                footers: [
                  Container(
                    padding: paddingH15,
                    child: pageRow,
                  ),
                  //页数选择
                  Container(
                    child: fluent.ComboBox<int>(
                      isExpanded: false,
                      value: _currentPerPage,
                      items: _perPages.map((e) {
                        return fluent.ComboBoxItem(
                          child: Text(e.toString()),
                          value: e,
                        );
                      }).toList(),
                      onChanged: (value) {
                        setState(() {
                          _currentPerPage = value!;
                          _currentPage = 1;
                          _resetData();
                        });
                      },
                    ),
                  ),
                  Container(
                    padding: paddingH15,
                    child: Text("$_currentPage - $_currentPerPage of $_total"),
                  ),
                  IconButton(
                    icon: backIcon,
                    onPressed: _currentPage == 1
                        ? null
                        : () {
                            _currentPage--;
                            var _nextSet = (_currentPage - 1) * _currentPerPage;
                            if (_nextSet < _currentPerPage) _nextSet = 0;
                            setState(() {
                              _resetData(start: _nextSet);
                            });
                          },
                  ),
                  IconButton(
                    icon: forwardIcon,
                    onPressed: _total - _currentPage * _currentPerPage <= 0
                        ? null
                        : () {
                            var _nextSet = _currentPage * _currentPerPage;
                            setState(() {
                              _currentPage++;
                              _resetData(start: _nextSet);
                            });
                          },
                  )
                ],
                //头部样式
                headerDecoration: BoxDecoration(
                    color: Colors.grey[400]!,
                    border: Border(
                        bottom:
                            BorderSide(color: AppTheme.accentColor, width: 1))),
                selectedDecoration: BoxDecoration(
                  border: Border(
                      bottom:
                          BorderSide(color: AppTheme.accentColor, width: 1)),
                  color: AppTheme.accentColor,
                ),
                headerTextStyle: whiteStyle,
                rowTextStyle: TextStyle(color: AppTheme.accentColor),
                selectedTextStyle: whiteStyle,
              ),
            ),
          ),
        ]));
  }

  ///构建操作栏
  generateActions() {
    return [
      Expanded(
        child: //输入内容
            Row(
          children: [
            Expanded(
                flex: 5,
                child: GyyTextInput(
                  '属性名称',
                  attributeNameController,
                  onSubmitted: (value) {
                    _filterData();
                  },
                )),
            sizeBoxH10,
            Expanded(
                flex: 5,
                child: GyyTextInput(
                  '属性code：',
                  attributeCodeController,
                  onSubmitted: (value) {
                    _filterData();
                  },
                ))
          ],
        ),
      ),
      TextButton(
        onPressed: () => {_filterData()},
        child: const Text("搜索").margin(const fluent.EdgeInsets.all(5)),
      ),
      sizeBoxH10,
      fluent.FilledButton(
          child: const Text(StringConstant.add),
          onPressed: () async {
            if (!checkInput()) {
              return;
            }
            var name = attributeNameController.text;
            var code = attributeCodeController.text;
            //添加数据
            addOne(name, code);
            //刷新数据
            loadAll();
          }),
      sizeBoxH10,
      fluent.Button(
        child: const Text(StringConstant.edit),
        onPressed: () async {
          if (!isSelectItem()) {
            showMessage(context, "请选择一条数据，进行编辑");
            return;
          }
          Map<String, dynamic> map = getSelectItem();
          var res = await showWidgetDialog(
              context,
              EditAttributePage(
                  map['id'], map['attributeName'], map['attributeCode']));
          fluent.debugPrint(res);
          if (DialogConstant.ok == res) {
            showMessage(context, StringConstant.saveSuccess);
            loadAll();
          }
        },
      ),
      sizeBoxH10,
      fluent.FilledButton(
          //自定义按钮的颜色
          style: fluent.ButtonStyle(
              backgroundColor: fluent.ButtonState.resolveWith(
            (states) => fluent.Colors.errorPrimaryColor,
          )),
          child: Text('删除'),
          onPressed: () async {
            if (!isSelectItem()) {
              showMessage(context, "请选择一条数据，进行编辑");
              return;
            }
            var id = getSelectItem()['id'];
            String? res = await showContentDialog(context, '删除选中的数据？');
            fluent.debugPrint(res);
            if (DialogConstant.ok == res) {
              deleteOne(id);
            }
          }),
    ];
  }

  isSelectItem() {
    if (_selectedList.isEmpty && selectedSub.isEmpty) {
      return false;
    }
    return true;
  }

  getSelectItem() {
    var item = _selectedList.isEmpty ? selectedSub : _selectedList[0];
    return item;
  }

  List<Map<String, dynamic>> _generateData(List<AttributeBean> _list) {
    List<Map<String, dynamic>> temps = [];
    for (var data in _list) {
      temps.add({
        "id": data.id,
        "attributeName": data.attributeName,
        "attributeCode": data.attributeCode,
        "attributeLevel": data.attributeLevel,
        "createTime": data.createTime.toString()
      });
    }
    return temps;
  }
}

///构建头部
_generateHeader() {
  return [
    DatatableHeader(text: "name", value: "attributeName", sortable: true),
    DatatableHeader(text: "code", value: "attributeCode", sortable: true),
    DatatableHeader(
      text: "level",
      value: "attributeLevel",
      sortable: true,
    ),
    DatatableHeader(
      text: "time",
      value: "createTime",
      sortable: false,
    )
  ];
}
